package com.cola.action;

import com.alibaba.fastjson.JSON;
import com.cola.common.ConstCommon;
import com.cola.entity.ActionResult;
import com.cola.enums.ErrorCode;
import com.cola.enums.ResultType;
import com.cola.service.UserService;
import com.cola.utils.Struts2Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;

/**
 * 登录Action
 */
public class LoginAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(LoginAction.class);
    private String username;
    private String password;

    /**
     * 跳转到登录页面
     * @return
     */
    public String toLogin() {
        return ConstCommon.LOGIN;
    }


    /**
     * 处理用户登录操作
     */
    public void doLogin() {
        ActionResult result = new ActionResult();
        logger.info("login--");
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)){
            if (StringUtils.isNotEmpty(password)){
                logger.info("userName:" + username);
                logger.info("password:" + password);
                Map<String, Object> userMap = UserService.getInstance().checkUser(username,password);
                if (userMap == null || userMap.isEmpty()) {
                    result.setResult(ResultType.ERROR.name());
                    result.setError_code(ErrorCode.LOGIN_ERROR.name());
                    result.setMsg(ErrorCode.LOGIN_ERROR.getDesc());
                } else {
                    result.setResult(ResultType.SUCCESS.name());
                    result.setError_code(ErrorCode.NO_ERROR.name());
                    setSessionAttribute(ConstCommon.USERCONTEXT, userMap);
                    setSessionAttribute(ConstCommon.USERMODULE,
                    JSON.toJSONString(UserService.getInstance().getUserModuleList((Integer)userMap.get("role_id"))));
                }
            } else {
                result.setResult(ResultType.EXCEPTION.name());
                result.setError_code(ErrorCode.LOGIN_EXCEPTION.name());
                result.setMsg(ErrorCode.LOGIN_EXCEPTION.getDesc());
            }
        } else {
            result.setResult(ResultType.ERROR.name());
            result.setError_code(ErrorCode.LOGIN_PARAMETER_ERROR.name());
            result.setMsg(ErrorCode.LOGIN_PARAMETER_ERROR.getDesc());
        }
        Struts2Utils.renderJson(result);
    }

    /**
     * 退出登录
     * @return
     */
    public String loginOut() {
        getRequest().getSession().invalidate();
        return ConstCommon.LOGIN;
    }





    public static Logger getLogger() {
        return logger;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
